package edu.gatech.gro.model.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.Item;
import edu.gatech.gro.model.ListItem;

public class ListItemJsonHandler extends JsonHandler {

	private static final String TAG = "LIST_ITEM_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		try {
			getResponse().setData(getListItems(json.getJSONArray("data")));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
	}

	@Override
	protected void parseData() {
		ListItem dataParsed = null;
		try {
			dataParsed = getListItem(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public static ArrayList<Item> getListItems(JSONArray array) {
		ArrayList<Item> dataParsed = new ArrayList<Item>();
		if (array != null) {
			try {
				for (int i = 0; i < array.length(); i++) {
					dataParsed.add(getListItem(array.getJSONObject(i)));
				}
			} catch (JSONException e) {
				Log.e(TAG, e.getMessage());
			}
		}
		return dataParsed;
	}

	public static ListItem getListItem(JSONObject obj) {
		ListItem li = new ListItem();
		try {
			parseAbstractObject(li, obj);
			li.setName(obj.getString("name"));
			li.setItemTypeId(obj.getInt("itemTypeId"));
			li.setGroceryStoreId(obj.getInt("groceryStoreId"));
			li.setBarCode(obj.getString("barCode"));
			li.setPrice(obj.getDouble("price"));
			li.setCurrency(obj.getInt("currency"));
			li.setChecked(obj.getBoolean("checked"));
			li.setQuantity(obj.getInt("quantity"));
			li.setCurrentQuantity(obj.getInt("currentQuantity"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return li;
	}
}
